package com.atguigu.flink.chapter05.sink;

import com.atguigu.flink.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

/**
 * @Author lzc
 * @Date 2022/7/5 10:19
 */
public class Flink04_Sink_Custom {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
    
    
      
        env
            .socketTextStream("hadoop162", 9999)
            .map(new MapFunction<String, WaterSensor>() {
                @Override
                public WaterSensor map(String value) throws Exception {
                    String[] data = value.split(",");
                
                
                    return new WaterSensor(data[0], Long.valueOf(data[1]), Integer.valueOf(data[2]));
                }
            })
            .keyBy(WaterSensor::getId)
            .sum("vc")
            .addSink(new MySQLSink());
            
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    
    
    
    
}
class MySQLSink extends RichSinkFunction<WaterSensor> {
    
    private Connection connection;
    
    @Override
    public void open(Configuration parameters) throws Exception {
        // 加载驱动
        Class.forName("com.mysql.jdbc.Driver");
        // 获取连接 alt+ctrl+f
        connection = DriverManager.getConnection("jdbc:mysql://hadoop162:3306/test?useSSL=false", "root", "aaaaaa");
        connection.setAutoCommit(false);
    }
    
    @Override
    public void close() throws Exception {
        if (connection != null) {
            connection.close();
        }
    }
    
    @Override
    public void invoke(WaterSensor value,
                       Context ctx) throws Exception {
        //
        // 定义sql语句
        //
//        String sql = "insert into sensor values(?,?,?)  on duplicate key update vc=?";
        String sql = "replace into sensor values(?,?,?)";
        // 得到一个预编译语句
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setString(1, value.getId());
        ps.setLong(2, value.getTs());
        ps.setInt(3, value.getVc());
//        ps.setInt(4, value.getVc());
        // 执行
        ps.execute();
        // 提交
        connection.commit();
        ps.close();
        
    }
}


/*

 */